#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <strings.h>

#define HTTPFILE "http-head.txt"
#define HTMLFILE "html1.html"
#define BACKLOG 5
//port 80
//sudo ./文件名 0 80
int ClientHandle(int newfd);

int ClientHandle(int newfd){
	int file_fd = -1;
	int ret;
	char buf[BUFSIZ] = {};
	
	do {
		ret = recv(newfd, buf, BUFSIZ, 0);
	}while(ret < 0 && errno == EINTR);
	if(ret < 0){
		perror("recv");
		exit(0);
	}else if(ret == 0){
		close(newfd);
		return 0;
	}else{
		printf("===================\n");
		printf("%s", buf);
		fflush(stdout);
	}

	bzero(buf, ret);
	if( (file_fd = open(HTTPFILE, O_RDONLY)) < 0){
		perror("open");
		exit(0);
	}
	if( (ret = read(file_fd, buf, BUFSIZ)) < 0){
		perror("read");
		exit(0);
	}
	printf("%s\n", buf);
	send(newfd, buf, ret, 0);
	close(file_fd);


	bzero(buf, ret);
	if( (file_fd = open(HTMLFILE, O_RDONLY)) < 0){
		perror("open");
		exit(0);
	}
	if( (ret = read(file_fd, buf, BUFSIZ)) < 0){
		perror("read");
		exit(0);
	}
	printf("%s\n", buf);
	send(newfd, buf, ret, 0);
	close(file_fd);
	close(newfd);
	return 0;

}

int main(int argc, char *argv[]){//利用传参的方式来获取端口号和IP地址
	
	int sockfd;
	int newfd;
	int add;
	struct sockaddr_in addr;

	if(argc < 3){
		fprintf(stderr, "%s<addr><port>\n", argv[0]);
		return 0;
	}

	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		perror("socket");
		return 0;
	}
	addr.sin_family = AF_INET;
	addr.sin_port = htons( atoi(argv[2]) ); // 字节序转换函数 主机字节序 小端 --> 网络字节序 大端

	if(inet_aton(argv[1], &addr.sin_addr) == 0){
		fprintf(stderr, "Invalid address\n");
		return 0;
	}

	int flag = 1, len = sizeof(int);
	if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,(const void*)&flag, len) == -1){
		perror("setsockopt");
		return 0;
	}//套接字设置 地址快速重用

	if( (add = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) ) == -1){
		perror("bind");
		return 0;
	}

	if(listen(sockfd, BACKLOG) == -1){
		perror("listen");
		return(0);
	}

	if((newfd = accept(sockfd, NULL, NULL)) < 0){
		perror("accept");
		return 0;
	}
	ClientHandle(newfd);
	
	close(sockfd);

	return 0;
}
